package logic

import (
	"context"
	"fmt"
	"zk/user_zk2/pkg"
	"zk/user_zk2/userRpc/models/cache"
	"zk/user_zk2/userRpc/models/mysql"

	"zk/user_zk2/userRpc/internal/svc"
	"zk/user_zk2/userRpc/userRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *userRpc.RegisterRequest) (*userRpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	findUser := mysql.User{}
	mysql.DB.Where("account=?", in.Account).Find(&findUser)

	if findUser.ID != 0 {
		return nil, fmt.Errorf("用户已存在，请前去登录")
	}

	user := mysql.User{
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
		Tel:      in.Tel,
	}

	sms, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
	if in.SmsCode != sms {
		return nil, fmt.Errorf("短信验证码错误！")
	}

	capt, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if in.CapCode != capt {
		return nil, fmt.Errorf("图形验证码错误！")
	}

	mysql.DB.Create(&user)

	return &userRpc.RegisterResponse{
		Id: int64(user.ID),
	}, nil
}
